import type {App} from 'vue';
import {useCache} from '@/hooks/web/useCache';
import CacheKeys from '@/constants/CacheKeys';

const {t} = useI18n(); // 国际化

export function hasPermission(app: App<Element>) {
    app.directive('hasPermission', (el, binding) => {
        const {wsCache} = useCache();
        const {value} = binding;
        const all_permission = '*:*:*';
        const permissions = wsCache.get(CacheKeys.USER_INFO).permissions;

        if (value && value instanceof Array && value.length > 0) {
            const permissionFlag = value;

            const hasPermissions = permissions.some((permission: string) => {
                return all_permission === permission || permissionFlag.includes(permission);
            });

            if (!hasPermissions) {
                el.parentNode && el.parentNode.removeChild(el);
            }
        } else {
            throw new Error(t('permission.hasPermission'));
        }
    });
}
